
mui.init();

mui('body').on('drag','#objectiveQuestionsBox',function () {
    event.stopPropagation();
})

//点击提示按钮,隐藏遮罩层和提示说明
mui('body').on('tap','.closeTipBtn',function () {
    $('.popMask').hide();
    $('.popTips').hide();
})

//用户左滑  下一题
document.addEventListener("swipeleft", function () {
    console.log('前往下一题');
    var objData = objectiveQueData;
    var ind = objData.q_index;
    var ty = objData.type;
    var id = objData.question_id;
    if(ind < objData.other.count_num - 1){
        record_answer(ty, id, ind);
        console.log(objData.userAnswer);
        console.log(objData.AnswerIng);
        objData.q_index++; //翻到下一题
    }else{
        mui.toast('作答完毕，请提交答案查看结果!', {duration: 1000,type: 'div'});
        objData.open_dtk();
    }
});

//用户右滑  返回上一题
document.addEventListener("swiperight", function () {
    var objData = objectiveQueData;
    console.log('返回上一题');
    if (objData.q_index == 0) {
        mui.toast('该题目是第一题哦', {duration: 1000,type: 'div'});
    } else {
        var ind = objData.q_index;
        var ty = objData.type;
        var id = objData.question_id;
        record_answer(ty, id, ind);
        console.log(objData.userAnswer);
        console.log(objData.AnswerIng);
        objData.q_index--; //翻到上一题
    }
});

var objectiveQueData;
mui.plusReady(function () {
    var self = plus.webview.currentWebview();
	//第一次打开练习,引导提示说明，记录状态，以后打开不显示提示
	if(!plus.storage.getItem("exerciseTips")){
	    $('.popMask').show();
	    $('.popTips').show();
	    plus.storage.setItem("exerciseTips",'true');
	}
    var catid = self.catid;
    //禁用ios右滑返回
    plus.webview.currentWebview().setStyle({ 'popGesture': 'none' });
    objectiveQueData = new Vue({
        el: '#objectiveQuestionsBox',
        data: {
            questionBoxStatus:0,
            questionErrorBoxStatus:0,
            errorTipsContent:"数据加载失败，可能网络异常",
            other: '',
            question_list: '',
            q_index: 0,
            collection_status: 0,
            type: 1,
            question_id: '',
            opIndex: '',
            userAnswer: [], //用户答题记录,该数组记录是否已经作答
            AnswerIng: [], //记录用户选择了哪个选项的数组
            an: 0, //0表示该题目已回答  1表示没有回答
        },
        mounted() {
            this.getObjectiveData();
        },
        watch: {
            q_index: function (val, oldVal) {
                var self = this;
                console.log(val);
                if (val == self.other.count_num) {
                    mui.toast('作答完毕，请提交答案查看结果!', {
                        duration: 1000,
                        type: 'div'
                    });
                    self.open_dtk();
                    return false;
                }
                self.type = self.question_list[val].type;
                self.question_id = self.question_list[val].id;
                self.collection_status = self.question_list[val].collection_status;
                console.log('从下标' + oldVal + '到了下标' + val + '的数据');
                console.log('题目类型为：' + self.type);
                console.log('此时题目ID为：' + self.question_id);
                if (self.type == 1) {
                    console.log('切换到单选题了');
                    if (self.userAnswer[self.q_index] == 1 && self.AnswerIng.length >= (self.q_index + 1)) { //说明改题目已经回答过
                        if (self.AnswerIng[self.q_index].length < 3) {
                            $('.dan_option').removeClass('active');
                        } else {
                            var opid = self.AnswerIng[self.q_index][2]; //获取该题目已经回答过的答案
                            if (opid) {
                                self.opIndex = opid;
                            } else {
                                self.$nextTick(function () {
                                    $('.dan_option').removeClass('active');
                                })
                            }
                        }
                    } else {
                        self.$nextTick(function () {
                            $('.dan_option').removeClass('active');
                        })
                    }
                } else if (self.type == 2) {
                    console.log('切换到多选题了');
                    if (self.userAnswer[this.q_index] == 1 && self.AnswerIng.length >= (self.q_index + 1)) {
                        if (self.AnswerIng[self.q_index].length < 3) {
                            self.$nextTick(function () {
                                $('.duo_option').removeClass('active');
                            })
                        } else {
                            self.$nextTick(function () {
                                var yid = self.AnswerIng[self.q_index][2];
                                if (yid.length > 0) {
                                    var len = yid.length;
                                    for (var i = 0; i < len; i++) {
                                        $(".duoxuan_" + yid[i]).addClass('active');
                                    }
                                } else {
                                    $('.duo_option').removeClass('active');
                                }
                            })
                        }
                    } else {
                        self.$nextTick(function () {
                            $('.duo_option').removeClass('active');
                        })
                    }
                } else if (self.type == 3) {
                    console.log('切换到判断题了');
                    if (self.userAnswer[self.q_index] == 1 && self.AnswerIng.length >= (self.q_index + 1)) {
                        if (self.AnswerIng[self.q_index].length < 3) {
                            self.$nextTick(function () {
                                $('.dj_zq').removeClass('active');
                                $('.dj_cw').removeClass('active');
                            })
                        } else {
                            self.$nextTick(function () {
                                var asw = self.AnswerIng[self.q_index][2];
                                if (asw == 1) {
                                    $('.dj_zq').addClass('active');
                                    $('.dj_cw').removeClass('active');
                                } else {
                                    $('.dj_cw').addClass('active');
                                    $('.dj_zq').removeClass('active');
                                }
                            })
                        }
                    } else {
                        self.$nextTick(function () {
                            $('.dj_zq').removeClass('active');
                            $('.dj_cw').removeClass('active');
                        })
                    }
                }
            },
        },
        methods: {
            clickRefresh:function(){
                this.getObjectiveData();
            },
            getObjectiveData: function () {
                var self = this;
                showWatting();
                var api_host = plus.storage.getItem('HOST_URL');
                mui.ajax({
                    url: api_host + '/api/questionbank/choice_question/brushing_questions',
                    data: {
                        'catid': catid,
                        'type': 'kg',
                    },
                    dataType: 'json',
                    type: 'get',
                    headers:{'User-Token':plus.storage.getItem('UserToken')},
                    timeout:3000,
                    success: function (msg) {
                        if (msg.code == 1) {
                            self.questionErrorBoxStatus = 0;
                            self.questionBoxStatus = 1;
                            self.question_list = msg.data.question;
                            self.type = self.question_list[0].type;
                            self.question_id = self.question_list[0].id;
                            self.other = msg.data.other;
                            self.collection_status = self.question_list[0].collection_status;
                            var c = self.other.count_num;
                            for (var i = 0; i < c; i++) {
                                self.userAnswer.splice(i, 1, 0);
                            }
                        } else {
                            self.questionErrorBoxStatus = 1;
                            self.questionBoxStatus = 0;
                            self.errorTipsContent = msg.msg;
                            mui.toast(msg.msg, {duration: 1500,type: 'div'});
                        }
                    },
                    error: function (xhr, type, errorThrown) {
                        self.questionErrorBoxStatus = 1;
                        mui.toast('加载失败!', {duration: '200',type: 'div'});
                    },
                    complete:function () {
                        plus.nativeUI.closeWaiting();
                    }
                });
            },
            xuanzhong_danxuan_option: function (e) {
                var self = this;
                //单选题点击选项
                self.opIndex = e.target.getAttribute('option-id');
                var qid = e.target.getAttribute('qid');
                self.an = 1;
                self.userAnswer.splice(self.q_index, 1, 1);
                if (self.AnswerIng[self.q_index]) {
                    self.AnswerIng[self.q_index].splice(2, 1, self.opIndex);
                } else {
                    var answering = [self.type, qid, self.opIndex];
                    self.AnswerIng.push(answering);
                }

                console.log(self.userAnswer);
                console.log(self.AnswerIng);

                mui.toast('进入下一题...', {
                    duration: 600,
                    type: 'div'
                });
                setTimeout(function () {
                    self.q_index++;
                }, 500)
            },
            xuanzhong_duoxuan_option: function (e) {
                //多选题点击选项
                var opid = e.target.getAttribute('option-id');
                if ($('.duoxuan_' + opid).hasClass('active')) {
                    $('.duoxuan_' + opid).removeClass('active');
                } else {
                    $('.duoxuan_' + opid).addClass('active');
                }
            },
            dj_zq: function (e) {
                //判断题点击正确
                $('.dj_zq').addClass('active');
                $('.dj_cw').removeClass('active');
                this.an = 1;
                var id = e.target.getAttribute('qid');
                if (this.q_index + 1 == objectiveQueData.other.count_num) {
                    var answer = [3, id, 1];
                    if (this.userAnswer[this.q_index] == 0) {
                        this.AnswerIng.push(answer);
                    } else {
                        this.AnswerIng.splice(this.q_index, 1, answer);
                    }
                }
                // this.userAnswer.splice(this.q_index,1,1);
            },
            dj_cw: function (e) {
                var id = e.target.getAttribute('qid');
                //判断题点击错误
                $('.dj_cw').addClass('active');
                $('.dj_zq').removeClass('active');
                this.an = 1;
                if (this.q_index + 1 == objectiveQueData.other.count_num) {
                    var answer = [3, id, 0];
                    if (this.userAnswer[this.q_index] == 0) {
                        this.AnswerIng.push(answer);
                    } else {
                        this.AnswerIng.splice(this.q_index, 1, answer);
                    }
                }
            },
            open_dtk: function () {
                //显示答题卡
                $('.popMask').show();
                $('.popCard').animate({
                    'bottom': '0%'
                }, 300).show();
            },
            yc_dtk: function () {
                //隐藏答题卡
                $('.popMask').hide();
                $('.popCard').animate({
                    'bottom': '-100%'
                }, 300).hide(300);
                $('.popTips').hide();
            },
            add_collection: function () {
                questionCollection(this.question_id, this.question_list[this.q_index]['category'],objectiveQueData);
            },
            open_jc: function () {
                //打开纠错界面
                mui.openWindow({
                    url: 'errorCorrection.html',
                    extras: {
                        'question_id': this.question_id,
                        'category': this.question_list[this.q_index]['category']
                    },
                    createNew: false,
                    show: {
                        autoShow: true,
                        aniShow: 'pop-in',
                        duration: 400
                    },
                    waiting: {
                        autoShow: false,
                    }
                })
            },
            tijiaojieguo: function () {
                //提交并查看结果
                $('.popMask').hide();
                $('.popCard').animate({
                    'bottom': '-100%'
                }, 300).hide(300);
                plus.storage.setItem('dati_jilu', JSON.stringify(this.AnswerIng));
                mui.openWindow({
                    url: 'exercisesResult.html',
                    extras: {
                        'category': 1,
                        'category_id': catid,
                    },
                    createNew: false,
                    show: {
                        autoShow: true,
                        aniShow: 'pop-in',
                        duration: 400
                    },
                    waiting: {
                        autoShow: false,
                    }
                })
            },
            tiaozhuan_que: function (ind) {
                console.log('手动跳到下标为' + ind);
                //点击答题卡小圆球跳转题目
                this.q_index = ind;
                this.yc_dtk();
            },
            back_but: function () {
                //用户点击返回
                var btnArray = ['继续作答', '退出'];
                mui.confirm('当前练习未完成，确定退出？', '提示', btnArray, function (e) {
                    if (e.index == 0) {
                        console.log('继续作答');
                    } else {
                        mui.openWindow({
                            url: '../columns/questionBank.html',
                            createNew: false,
                            show: {
                            autoShow: true,
                                aniShow: 'pop-in',
                                duration: 400
                            },
                            waiting: {
                                autoShow: false,
                                }
                        })
                        //关闭当前webview
                        var ws=plus.webview.currentWebview();
						plus.webview.close(ws);
                    }
                })
            }
        }
    })
})

//记录用户选择的答案
function record_answer(ty, id, ind) {
    var objData = objectiveQueData;
    if (ty == 1) { //单选题
        var iii = ind + 1;
        console.log('正在记录单选题第' + iii + '题')
        if (objData.userAnswer[ind] == 0) {
            console.log('单选题未选择滑动开始开始下一题');
            var answering = [objData.type, id, ''];
            objData.AnswerIng.push(answering);
            objData.userAnswer.splice(ind, 1, 0);
        }
    } else if (ty == 2) { //表示当前题目是多选题
        var iii = ind + 1;
        console.log('正在记录多选题第' + iii + '题')
        //表示该题目还未作答
        var obj = $('.duo_option');
        var id_arr = [];
        $.each(obj, function (index, value) {
            if ($(this).hasClass('active')) {
                id_arr.push($(this).attr('option-id'));
            }
        })
        if (id_arr.length == 0) {
            objData.userAnswer.splice(ind, 1, 0);
        } else {
            objData.userAnswer.splice(ind, 1, 1);
        }
        if (objData.AnswerIng[ind]) {
            //回答状态为0  答案数组中该项存在 表示用户返回重新作答之前没回答的题目
            objData.AnswerIng[ind].splice(2, 1, id_arr);
        } else {
            // 答案数组中该项不存在 表示是第一次作答 正常逻辑作答
            var answer = [ty, id];
            answer.push(id_arr);
            objData.AnswerIng.push(answer);
        }
    } else if (ty == 3) { //表示当前题目是判断题
        var iii = ind + 1;
        console.log('正在记录判断题第' + iii + '题')
        //返回作答之前没回答的
        if ($('.dj_zq').hasClass('active')) {
            var answer = [3, id, 1];
            objData.userAnswer.splice(ind, 1, 1);
        } else if ($('.dj_cw').hasClass('active')) {
            var answer = [3, id, 0];
            objData.userAnswer.splice(ind, 1, 1);
        } else {
            var answer = [3, id, ''];
            objData.userAnswer.splice(ind, 1, 0);
        }
        if (objData.AnswerIng[ind]) {
            objData.AnswerIng.splice(ind, 1, answer);
        } else {
            objData.AnswerIng.push(answer);
        }
    }
}

var backButtonPress = 0;
mui.back = function(event) {
    backButtonPress++;
    if (backButtonPress > 1) {
        setTimeout(function(){
            plus.webview.currentWebview().close();
        }, 100)
    } else {
        plus.nativeUI.toast('再按一次退出答题');
    }
    setTimeout(function() {
        backButtonPress = 0;
    }, 2000);
    return false;
};
